using System;
using System.IO;
namespace MKDS_Course_Editor
{
    public class lz77DeCompression
 {
 private char ReferencePrefix;
 private int ReferencePrefixCode;
 private int ReferenceIntBase;
 private int ReferenceIntFloorCode;
 private int ReferenceIntCeilCode;
 private int MaxStringDistance;
 private int MinStringLength;
 private int MaxStringLength;
 private int MaxWindowLength;
  
 public lz77DeCompression()
 {
 this.ReferencePrefix ='`';
 this.ReferencePrefixCode = (int)this.ReferencePrefix;
 this.ReferenceIntBase = 96;
 this.ReferenceIntFloorCode =(int)' ';
 this.ReferenceIntCeilCode = this.ReferenceIntFloorCode + this.ReferenceIntBase -1;
 this.MaxStringDistance = (int)Math.Pow(this.ReferenceIntBase ,2)-1;
 this.MinStringLength = 5;
 this.MaxStringLength = (int)Math.Pow(this.ReferenceIntBase, 1) - 1 + this.MinStringLength;
 this.MaxWindowLength = this.MaxStringDistance + this.MinStringLength;
 }

 private int decodeReferenceInt(string words, int width)
 {
 int value;
 int i;
 int charcode;
 value = 0;

 for (i = 0; i < width;i++ )
 {
 value *= this.ReferenceIntBase;
 charcode = (int)words[i];

 if ((charcode >= this.ReferenceIntFloorCode) && (charcode <= this.ReferenceIntCeilCode))
 {
 value += charcode - this.ReferenceIntFloorCode;
 }


 /* else
 {
 Response.Write ( "<script type=\"javascript\">alert("+ charcode+")<//script>");
 }*/
 }
 return value;
 }
  
 private int decodeReferenceInt(char words, int width)
 {
 int value;
 int i;
 int charcode;
 value = 0;
  
 for (i = 0; i < width; i++)
 {
 value *= this.ReferenceIntBase;
 charcode = (int)words;
  
 if ((charcode >= this.ReferenceIntFloorCode) && (charcode <= this.ReferenceIntCeilCode))
 {
 value += charcode - this.ReferenceIntFloorCode;
 }
  
 
/* else
 {
 Response.Write ( "<script type=\"javascript\">alert("+ charcode+")<//script>");
 }*/
 }
 return value;
 }

 private int decodeReferenceLength(char words)
 {
 return decodeReferenceInt(words, 1) + this.MinStringLength;
 }

 public string decompress(string words)
 {
 string decompressed;
 int pos,distance,length;
 int getSubString;
 char currentChar;
 char nextChar;
 decompressed ="";
 pos = 0;
 while (pos < words.Length)
 {
 currentChar = words[pos];
 if (currentChar!=this.ReferencePrefix)
 {
 decompressed += currentChar;
 pos++;
 }
 else
 {
 nextChar = words[pos + 1];
 if (nextChar != this.ReferencePrefix)
 {
 distance = decodeReferenceInt(words.Substring(pos + 1, 2), 2);
 length = decodeReferenceLength (words[pos+3]);
 getSubString=decompressed.Length - distance - length;
 decompressed += decompressed.Substring(getSubString, length);
 pos += this.MinStringLength - 1;
  
 }
 else
 {
 decompressed += this.ReferencePrefix;
 pos += 2;
 }
 }
 }
 return decompressed;
 }
 }
 
 


}
